package com.junxian.demo.write;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.fastjson.JSON;
import com.junxian.demo.model.VActiveAlarmVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 内容写入excel 表格
 */
public class EasyExcelWrite {

    private final static Logger logger = LoggerFactory.getLogger(EasyExcelWrite.class);

    public static void main(String[] args) {
        simpleWrite();
    }

    /**
     * 活动告警列表名称
     */
    private static final String ALARM_FILENAME = "活动告警列表";

    /**
     * @description 简单写入表格
     * @author sunjx
     * @date 2020/9/28 17:48
     * @param
     * @return void
     **/
    private static void simpleWrite(){
        // 文件输出位置
        String outPath = "D:\\bigData\\esayexcel.xlsx";
        String readPath = "D:\\bigData\\活动告警列表.xlsx";
        List<VActiveAlarmVO> list = new ArrayList<>();
        try {
            // sheetNo --> 读取哪一个 表单
            // headLineMun --> 从哪一行开始读取( 不包括定义的这一行，比如 headLineMun为2 ，那么取出来的数据是从 第三行的数据开始读取 )
            // clazz --> 将读取的数据，转化成对应的实体，需要 extends BaseRowModel
            Sheet sheet = new Sheet(1, 1, VActiveAlarmVO.class);
            List<Object> readList = EasyExcelFactory.read(new FileInputStream(readPath), sheet);
            for (Object obj : readList) {
                list.add((VActiveAlarmVO) obj);
            }
            logger.info("查看VActiveAlarmVO结果集" + JSON.toJSONString(list));

            ExcelWriter excelWriter = EasyExcelFactory.getWriter(new FileOutputStream(outPath));
            // 表单
            Sheet sheets = new Sheet(1,0);
            sheet.setSheetName("第一个Sheet");
            sheet.setColumnWidthMap(setColumnWidth());
            excelWriter.write1(list, sheet);
            // 记得 释放资源
            excelWriter.finish();
        } catch (FileNotFoundException e) {
            logger.error("simpleWrite error:{}", e);
            e.printStackTrace();
        }
    }

    /**
     * @description 设置列宽
     * @author sunjx
     * @date 2020/9/2 15:06
     * @param
     * @return java.util.Map
     **/
    private static Map setColumnWidth(){
        Map columnWidth = new HashMap();
        columnWidth.put(0,10000);
        columnWidth.put(1,6000);
        columnWidth.put(2,4000);
        columnWidth.put(3,6000);
        columnWidth.put(4,7000);
        columnWidth.put(5,5000);
        columnWidth.put(6,5000);
        return columnWidth;
    }
}
